import 'package:book_manager_app/app/modules/add_book/models/add_book_req.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:book_manager_app/app/modules/add_book/models/book.dart';
import 'package:book_manager_app/app/modules/home/request/home_request.dart';
import 'package:http_manager/result_analyzed.dart';
import '../../../utils/common/result_code.dart';
import 'package:book_manager_app/app/utils/common/base_controller.dart';
import 'package:book_manager_app/app/modules/add_book/request/book_request.dart';

import '../models/tanshu_book_model.dart';


class AddBookController extends BaseController {

  final model = AddBookReq().obs;
  final models = <Book>[].obs;
  final checkList = <Book>[].obs;

  final TextEditingController nameVC = TextEditingController();
  final TextEditingController isbnVC = TextEditingController();
  final TextEditingController authorVC = TextEditingController();
  final TextEditingController categoryVC = TextEditingController();
  final TextEditingController pressVC = TextEditingController();
  final TextEditingController originalPriceVC = TextEditingController();
  final TextEditingController salePriceVC = TextEditingController();
  final TextEditingController stockVC = TextEditingController();

  // 默认服务器有这本书
  bool isHave = true;

  @override
  onInit() {
    super.onInit();
    state.value = ResultCode.success;

    /// 1. 补货时，识别条形码，查询数据库是否有该条形码的的信息
    /// 2. 如果数据库有该书的信息，弹出输入框，填写补货数量。
    /// 3. 如果没有该书的信息，调用第三方 api 查询该书的信息，获取成功后，保存到数据库。
    getBookInfo();
  }

  Future<void> getBookInfo() async {
    var isbn = Get.arguments;
    showLoadingMessage("正在查询...");
    final result = await BookRequest.getBookInfo(isbn);
    if (result.success) {
      if (result.data is Map && result.data.containsKey("list")) {
        final list = result.data["list"];
        // 服务器没有这本书，需要调用第三方去查询
        if (list.isEmpty) {
          isHave = false;
          getTanshuapi(isbn);
        }else {
          dismissLoading();
          model.value = AddBookReq.fromJson(list.first);
          await setupBookInfo();
        }
      } else {
        dismissLoading();
        model.value = AddBookReq.fromJson(result.data);
        setupBookInfo();
      }
    }else {
      dismissLoading();
    }
  }

    
  void getTanshuapi(isbn) async {
    showLoadingMessage("本地服务器未查到，正在使用第三方查询...");
    // await Future.delayed(const Duration(milliseconds: 500));
    final result = await BookRequest.tanshuapi(isbn);
    dismissLoading();
    if (result.code == "1" && result.data != null) {
      final tanshuBook = TanshuBook.fromJson(result.data);
      model.value = AddBookReq(
        name: tanshuBook.title,
        isbn: tanshuBook.isbn,
        imageUrl: tanshuBook.img,
        author: tanshuBook.author,
        keyword: tanshuBook.keyword,
        publisher: tanshuBook.publisher,
        referencePrice: double.tryParse(tanshuBook.price??"0") ?? 0,
        purchasePrice: double.tryParse(tanshuBook.price??"0") ?? 0,
        salePrice: double.tryParse(tanshuBook.price??"0") ?? 0,
        discountPrice: double.tryParse(tanshuBook.price??"0") ?? 0,
        inventory: 100,
      );
      setupBookInfo(); 
    }
  }

  setupBookInfo() {
    nameVC.text = model.value.name ?? "";
    isbnVC.text = model.value.isbn ?? "";
    authorVC.text = model.value.author ?? "";
    categoryVC.text = model.value.keyword ?? "";
    pressVC.text = model.value.publisher ?? "";
    originalPriceVC.text = model.value.purchasePrice.toString();
    salePriceVC.text = model.value.salePrice.toString();
    // stockVC.text = model.value.inventory.toString();
    model.refresh();
  }

  submit() {
    if (nameVC.text.isEmpty) {
      showAlertMessage("请输入书名");
      return;
    }else if (isbnVC.text.isEmpty) {
      showAlertMessage("请输入书号");
      return;
    }else if (authorVC.text.isEmpty) {
      showAlertMessage("请输入作者");
      return;
    }else if (pressVC.text.isEmpty) {
      showAlertMessage("请输入出版社");
      return;
    }else if (originalPriceVC.text.isEmpty) {
      showAlertMessage("请输入进价");
      return;
    }else if (salePriceVC.text.isEmpty) {
      showAlertMessage("请输入销售价");
      return;
    }else if (stockVC.text.isEmpty) {
      showAlertMessage("请输入库存");
      return;
    }

    model.value.name = nameVC.text;
    model.value.isbn = isbnVC.text;
    model.value.author = authorVC.text;
    model.value.bookId = model.value.id;
    model.value.keyword = categoryVC.text;
    model.value.publisher = pressVC.text;
    model.value.purchasePrice = double.tryParse(originalPriceVC.text) ?? 0;
    model.value.salePrice = double.tryParse(salePriceVC.text) ?? 0;
    final stock = stockVC.text == "" ? "0" : stockVC.text;
    model.value.inventory = int.tryParse(stock) ?? 0;

    if (isHave == false) {
      addBookInfo();
    }else {
      updateBookInfo();
    }
  }

  // 新增图书
  addBookInfo() async {
    showLoadingMessage("新增图书...");
    final result = await BookRequest.addBook(model.value);
    dismissLoading();
    if (result.success) {
      showMessage("新增成功！");
      Get.back();
    }
  }

  // 更新图书信息、包括图书的库存信息
  updateBookInfo() async {
    showLoadingMessage("正在更新库存...");
    
    final result = await BookRequest.addStock(model.value);
    dismissLoading();
    if (result.success) {
      showMessage("更新成功！");
      Get.back();
    }
  }


}

